import React, {Component} from 'react'
import {inject, observer} from 'mobx-react';
import {observable, action, toJS} from 'mobx';
import {Tabs, Tooltip, Spin} from 'antd'

const TabPane = Tabs.TabPane

import WeaUtils from "../../Component/wea-utils"

const {DateFormat, DateAddition} = WeaUtils
import { WeaTableNew, WeaLogView } from "comsMobx";
import TopSearchPanel from './Weibo/TopSearchPanel'
import {getStrongSearchs} from './Weibo/WeiboUtils.js'
import Weibo from './Weibo/index'

import Fans from "./Fan"
import Attentions from "./Attention"
import ShareToMes from "./ShareToMe"
import {WeaNewScrollPagination} from 'ecCom'
import { Button } from "antd";
import {WeaLocaleProvider} from "ecCom";
import {WeaTab} from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;
const { WeaTable } = WeaTableNew;
const getPointerX = (obj) => {
    let parObj=obj;
    let left=obj.offsetLeft;
    while(parObj=parObj.offsetParent){
        left+=parObj.offsetLeft;
    }
    return left;
}

const getPointerY = (obj) => {
    let parObj=obj;
    let top=obj.offsetTop;
    while(parObj = parObj.offsetParent){
        top+=parObj.offsetTop;
    }
    return top;
}

@inject('blogMyBlog')
@observer
class RightContainer extends Component {

  constructor(props) {
    super(props);
    let {cardType} = props;
    let {weiboType} = props;
    let {selectedKey} = props;
      let url = window.location.href;
      if(url.indexOf("/comment")>0){
          weiboType = 2;
      }else if(url.indexOf("/zan")>0){
        weiboType = 3;
      }else if(url.indexOf("/atMe")>0){
        weiboType = 4;
      }else if(url.indexOf("/homepage")>0){
        weiboType = 11;
        cardType = 1;
    }
   
    this.state = {...this.initData(), cardType: cardType, weiboType: weiboType,selectedKey:selectedKey,blogNote:''}

    this.getWeiboListByAction = this.getWeiboListByAction.bind(this);
  }

  initData = () => {
    return {
      startSearch: false,
      searching: false,
      searchForm: {},
      weiboType: 1,
      weiboGroup: "1",
      selectedKey:"-1"
    }
  }

  componentDidMount() {
    const { blogMyBlog,cardType } = this.props;
    blogMyBlog.doInit(cardType);
  }

  componentWillReceiveProps(nextProps) { 
    const { blogMyBlog } = this.props;

    if (nextProps.cardType != this.state.cardType) {
      this.setState({...this.initData(), cardType: nextProps.cardType})
      blogMyBlog.doInit(nextProps.cardType);
    }

   
  }

  get currentType() {
    let {cardType} = this.props, {weiboType} = this.state;
    if (cardType * 1 == 1 && weiboType > 2) {
      weiboType = 1;
    }
    return cardType * 10 + weiboType * 1
  }

  get selectedType() {
    let {cardType} = this.props, {selectedKey} = this.state;
    if(selectedKey==null){
      selectedKey = 0;
    }else if(selectedKey=="-1"){
      selectedKey  = 1;
    }else if(selectedKey=="-2"){
      selectedKey  = 2;
    }else if(selectedKey=="-3"){
      selectedKey  = 3;
    }else{
      selectedKey = 1;
    }
    return cardType * 10 + selectedKey * 1
  }

  set currentType(value) {
    this.setState({weiboType: value})
  }

  get currentGroup() {
    return this.state.weiboGroup
  }

  set clear(value) {
    if (value) this.setState({...this.initData()})
  }

  getDateInterval=(res)=>{
      let startDate = DateFormat(res.startDate, "yyyy-MM-dd");
      let endDate = DateFormat(res.endDate, "yyyy-MM-dd");
      this.setState({
          startDate:startDate,
          endDate:endDate
    })
    let param  = {startDate:startDate,endDate:endDate};
    const { blogMyBlog } = this.props;
    blogMyBlog.doExeclMyBolgParamInit(param);

  }
  getFormParams(){
    const {
      searchAdForShareTable
    } = this.props.blogMyBlog;
    const { form } = searchAdForShareTable;
    let params =
      (searchAdForShareTable.form &&
        searchAdForShareTable.form.getFormParams()) ||
      {};
     return params;
  }
  
  getTabButtonsAd(mainpage,ecId) {
    const {
      searchAdForShareTable
    } = this.props.blogMyBlog;
    let params = this.getFormParams();
    const { form } = searchAdForShareTable;
    return [
      <Button ecId={`${ecId}_Button@yqbvau@search`}
        type="primary"
        onClick={() => {
          if(typeof(params.groupId)=="undefined"){
            params.groupId = "-1";
          }
          this.changeWeiboType(mainpage, params.groupId)
          searchAdForShareTable.show = false;
        }}
      >
        {getLabel(197, "搜索")}
      </Button>,
      <Button ecId={`${ecId}_Button@bqyfoi@reset`} type="ghost" onClick={() => form.reset()}>
        {getLabel(27088, "重置")}
      </Button>,
      <Button ecId={`${ecId}_Button@b84hc0@ghost`} type="ghost" onClick={() => (searchAdForShareTable.show = false)}>
        {getLabel(31129, "取消")}
      </Button>
    ];
  }


  onEnterSearch = () => {
      const {
          searchAdForShareTable
      } = this.props.blogMyBlog;
      let params =
          (searchAdForShareTable.form &&
              searchAdForShareTable.form.getFormParams()) ||
          {};
 searchAdForShareTable.show = false;
      this.getWeiboList(null,params);
  }

  render() {
    let {setKeywords} = this.props.blogMyBlog
    const {
      searchAdForShareTable
    } = this.props.blogMyBlog;
    const { form, show, conditioninfo } = searchAdForShareTable;
    let {
        cardType, userInfo, weiboCKEditorConfig, weiboGroup, weiboList, topHeight, systemWorkLog, fanList,
        basicInfo: {countData = {}},
        attentionList, checkAttention, changeGroup, defaultTemplate, loading, keyWords,selectGroup,cancelAttentionSelect
      } = this.props,
     
      {weiboType, startSearch} = this.state,
      containerHeight = topHeight - 120,
      commonProps = {
        userInfo: userInfo,
        height: containerHeight,
        systemWorkLog: systemWorkLog,
        //isReset: startSearch,
        defaultTemplate: defaultTemplate.defaultTemplate || {},
        weiboCKEditorConfig: weiboCKEditorConfig.appList
      },
      mainpage = [
        {id: 1,groupId:'-1', type: 11, name: getLabel(384389, "全部关注"), data: weiboList, others: commonProps, hasImage: true},
        {id: 2,groupId:'-2',  type: 12, name: getLabel(33847, "未读微博"), data: weiboList, others: commonProps, hasImage: true},
        {id: 4,groupId:'-5', type: 11, name:  getLabel(514285,'特别关注'), data: weiboList, others: commonProps, hasImage: true},
        {id: 3,groupId:'-3', type: 13, name: getLabel(513653, "分享给我"), data: weiboList, others: commonProps, hasImage: true}

      ],
      weibos = [
        {
          id: 1,
          type: 21,
          name: getLabel(26467, "微博"),
          data: weiboList,
          others: commonProps,
          hasScroll: true,
          hasEditor: true
        },
        {
          id: 2,
          type: 22,
          name: getLabel(675, "评论"),
          data: weiboList,
          others: commonProps,
          commentCount: countData.commentCount || 0
        },
        {id: 3, type: 23, name: getLabel(32942, "赞"), data: weiboList, others: commonProps},
        {id: 4, type: 24, name: getLabel(503746,"@我"), data: weiboList, others: commonProps}
      ],
      // {id: 4, type: 24, name: "@我", data: weiboList, others: commonProps}
      groups = weiboGroup.groupList || [],
      fans = fanList.attnList || [],
      attentions = attentionList.attentionList || [];
    let seq = 0
    groups.forEach(
      item => {
        const {groupId, groupName} = item
        if (groupId != "all" && groupId != "nogroup") {
          mainpage.push(
            {
              id: 5 + seq,
              type: 11,
              name: groupName,
              data: weiboList,
              others: commonProps,
              groupId: groupId,
              hasImage: true,
              weiboCKEditorConfig: weiboCKEditorConfig
            }
          )
          seq++
        }
      }
    )
   let tabDatas =  this.getTabsTitle(mainpage);
    return (
      <div className="wea-right-container">
        {
          cardType == 1 ? 
              <div>
             <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@grebwn`}
              datas ={tabDatas}
              keyParam="viewcondition"
              countParam="groupid"
              selectedKey= {this.state.selectedKey}
              leftStyle={{paddingRight:240}}
              onChange={this.changeWeiboType.bind(this, mainpage)}
              searchType={["base", "advanced"]}
              advanceHeight = {300}
              searchsAd={getStrongSearchs(form, conditioninfo, false, 2,this.onEnterSearch)}
              showSearchAd={show}
              buttonsAd={this.getTabButtonsAd(mainpage,this.props.ecId || '')}
              setShowSearchAd={() => (searchAdForShareTable.show = !show)}
              hideSearchAd={() => (searchAdForShareTable.show = false)}
              searchsBaseValue={
                (searchAdForShareTable.form.isFormInit &&
                  searchAdForShareTable.form.getFormParams() &&
                  searchAdForShareTable.form.getFormParams().content) ||
                ""
              }
              onSearch={() => {
                let params =
                (searchAdForShareTable.form &&
                  searchAdForShareTable.form.getFormParams()) ||
                {};
                
                this.getWeiboList(null,params);

              }}
              onSearchChange={value => {
                form.updateFields({ content: value });
              }}
            /> {this.getWeiboDom(1, mainpage, loading, keyWords)}</div>: ""
        }
      
        {
          cardType == 2 ? (
            <Tabs ecId={`${this && this.props && this.props.ecId || ''}_Tabs@7kzezo`}
              animation={false}
              activeKey={weiboType + ""}
              size="small"
              onChange={this.changeWeiboType.bind(this, weibos)}
              tabBarExtraContent={
                weiboType == 1 ? (
                  <TopSearchPanel ecId={`${this && this.props && this.props.ecId || ''}_TopSearchPanel@q8pkay`}
                  ref="TopSearchPanel"
                  pfn={this.getDateInterval.bind(this)}
                  requestData={this.getWeiboList.bind(this, null)}
                  onChange={v => setKeywords(v)}
                />
                ) : ""
              }
            >
              {this.getTabsDom(2, weibos, loading, keyWords)}
            </Tabs>
          ) : ""
        }
        {
          cardType == 3 ? (
            <Fans ecId={`${this && this.props && this.props.ecId || ''}_Fans@5volb2`}
              height={topHeight}
              data={fans}
              changeGroup={changeGroup}
            />
          ) : ""
        }
        {
          cardType == 4 ? (
            <Attentions ecId={`${this && this.props && this.props.ecId || ''}_Attentions@02spxe`}
              ref="attentions"
              weiboGroup={weiboGroup}
              height={topHeight}
              onCheck={checkAttention}
              changeGroup={changeGroup}
              selectGroup={selectGroup}
            />
          ) : ""
        }
        {
          cardType == 5 ? (
            <ShareToMes ecId={`${this && this.props && this.props.ecId || ''}_ShareToMes@ueyh4t`}
              ref="shareToMes"
              weiboGroup={weiboGroup}
              height={topHeight}
              onCheck={checkAttention}
              onCheck={checkAttention}
              changeGroup={changeGroup}
              cancelAttentionSelect={cancelAttentionSelect}
            />
          ) : ""
        }

      </div>
    )
  }

  // 获取tab页title
  getTabsTitle = (tabs) => {
   let tabDatas = [];
    tabs.map(
      (item, key) => {
        let {id,name,commentCount,groupId} = item;
        tabDatas.push({title:name,viewcondition:""+groupId});
      }
    )
    return tabDatas;
  }

  getWeiboDom= (cardType, tabs, loading, keyWords) => {
    return tabs.map(
      (item, key) => {
        let {id, group, type, name, data, others, hasScroll, hasEditor, hasImage, commentCount} = item,
          hasData = data.discussList && data.discussList.length > 0, end = !data.__hasData,
          topHeight = this.props.topHeight - 51;
        return (
            <WeaNewScrollPagination ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScrollPagination@jd1u0h@${key}`} toTop={true} onScrollEnd={this.fetchData} height={topHeight} loading={loading}>
              <div className="wea-blog-spin-con">
                <Weibo ecId={`${this && this.props && this.props.ecId || ''}_Weibo@8pwchk@${key}`}
                  {...others}
                  records={data}
                  blogType={cardType * 100 + id * 1}
                  hasScroll={hasScroll || false}
                  hasEditor={hasEditor || false}
                  hasImage={hasImage || false}
                  keyWords={keyWords}
                />
                {hasData && loading &&
                <div className="align-center pt10"><Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@1dczgv@${key}`} tip={getLabel(384399, "加载中，请稍候...")}/></div>}
                {hasData && !loading && end && <div className="align-center pt10">{getLabel(384398, "没有微博了")}</div>}
              </div>
            </WeaNewScrollPagination>
        )
      }
    )
  }
  
  
   saveBlogNote = () => {
     const save = this.props.blogMyBlog.saveNote;
        save({content:this.state.blogNote,saveType:"append"})


    }

 onBlogScroll = () => {
    if(!this.props.blogMyBlog.isBlogNote=="0") {
        let menu=document.getElementById("popmenu");
        if(menu){
            menu.style.display="none";
        }
    }
   }

    showBlogBtn = ()  =>{
      if(this.props.blogMyBlog.isBlogNote=="0"){
          return ;
      }
        let menu=document.getElementById("popmenu");
        let ddd=document.getElementById("blognote");
        let demo = window.getSelection();

        if(demo.toString().length<1||demo.toString()==undefined){
        }
        else {

            let str = demo.toString().replace(/<[^>]+>|&[^>]+;/g,"").trim();
            this.setState({blogNote:str})
        }

        let ddssd = this.state.blogNote;
        ddd.onclick=function(event){
            let e=event?event:window.event;
            let left = getPointerX(ddd);
            let top = getPointerY(ddd);

            menu.style.left=(e.clientX-left+document.documentElement.scrollLeft) -2+"px";
            menu.style.top=(e.clientY-top+document.documentElement.scrollTop) -31+"px";
            if((demo.toString().replace(/<[^>]+>|&[^>]+;/g,"").trim()==ddssd)||(demo.toString().length<1||demo.toString()==undefined)){
                menu.style.display="none";
            }else{
                menu.style.display="block";
            }
            menu.style.zIndex="999";
        }


    }

  getTabsDom = (cardType, tabs, loading, keyWords) => {
    return tabs.map(
      (item, key) => {
        let {id, group, type, name, data, others, hasScroll, hasEditor, hasImage, commentCount} = item,
          hasData = data.discussList && data.discussList.length > 0, end = !data.__hasData,
          topHeight = this.props.topHeight - 61;
        return (
          <TabPane ecId={`${this && this.props && this.props.ecId || ''}_TabPane@ahoxzk@tabpane${key}`}
            tab={
              // <Tooltip
              //     placement="bottomLeft"
              //     title={name}
              //     overlayStyle={{maxWidth: "200px"}}
              // >
              <div>
                <span title={name.split('').length > 10 ? name : ''}>{name}</span>
                {commentCount ? <span className="tip">{`(${commentCount})`}</span> : undefined}
              </div>
              // </Tooltip>
            }
            key={id}
          >
		  <div id="blognote" style={{"position":'relative'}} onMouseUp={this.showBlogBtn} >
                  {this.props.blogMyBlog.isBlogNote=="0"?"":
                      <div id='popmenu' style={{display:"none",width:30,height:22,"z-index": "999 !important","border":1,"position":"absolute","font-size":" 20px",
                          "cursor": "pointer",
                          "text-align": "center","line-height": 22}} title={getLabel(512297,'发送到微博便签')} onClick={this.saveBlogNote}><span className="icon-portal-content-o" /></div>}

            <WeaNewScrollPagination ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScrollPagination@i3w5fv@${key}`} toTop={true}  onScroll={this.onBlogScroll} onScrollEnd={this.fetchData} height={topHeight} loading={loading}>
              <div className="wea-blog-spin-con">
                <Weibo ecId={`${this && this.props && this.props.ecId || ''}_Weibo@h73tw8@${key}`}
                  {...others}
                  records={data}
                  blogType={cardType * 100 + id * 1}
                  hasScroll={hasScroll || false}
                  hasEditor={hasEditor || false}
                  hasImage={hasImage || false}
                  keyWords={keyWords}
                  ecmeType={this.props.blogMyBlog.isenableecme}
                />
                {hasData && loading &&
                <div className="align-center pt10"><Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@tk9lhu@${key}`} tip={getLabel(384399, "加载中，请稍候...")}/></div>}
                {hasData && !loading && end && <div className="align-center pt10">{getLabel(384398, "没有微博了")}</div>}
              </div>
            </WeaNewScrollPagination>
			</div>
          </TabPane>
        )
      }
    )
  }

  getWeiboList = (blogType, params) => {
    const {cardType, weiboList} = this.props,
      {currentPage, minUpdateid} = weiboList,
      {weiboType, searching, searchForm} = this.state
    let others = {},
      result = {};
    switch (cardType * 1) {
      case 1 :  //微博主页tab相关页面
        if (blogType) {  //非自定义分组对应的微博，有blogtype值。
          if (searching) {
            result = {
              ...searchForm,
              currentPage: currentPage + 1,
              groupId: "1"
            }
            this.searchWeiboMainPageListByAction(result)
          } else {
            if(blogType==10){
              params["currentPage"] = currentPage + 1
            }else if (blogType == 12) {  //未读微博列表
              result = {
                ...searchForm,
                minUpdateid: minUpdateid, //处理未读微博的特殊参数
                groupId: params || "1"
              
              }
            
            } else { //微博主页列表 及 自定义分组微博列表
              // result = {
              //   ...searchForm,
              //   currentPage: currentPage + 1,
              //   startDate:this.state.startDate,
              //   endDate: this.state.endDate,
              //   groupId: params || "1"
              // }
              params.currentPage = currentPage + 1
            }
            others = {type: blogType}
            this.getWeiboListByAction(others, params)
          }
        } else {
          
          params["currentPage"] =  1;
          if(this.selectedType==11){
            this.searchWeiboMainPageListByAction(params)
          }else if(this.selectedType==12){
            this.searchUnreadWeiboMainPageListByAction(params)
          }else if(this.selectedType==13){
            this.searchWeiboMainPageShareToMeListByAction(params)
          }else if(this.selectedType==10){
            this.searchWeiboMainPageAllListByAction(params)
          }else{
            this.searchWeiboMainPageListByAction(params)
          }
          this.props.changeReset(true)
          this.setState({searching: true, searchForm: params, startSearch: true, weiboType: weiboType})
        }
        break;
      case 2:
        if (blogType) {
          if (blogType == 21) {
            if (searching) {
              result = {
                ...searchForm,
                currentPage: currentPage + 1
              }
              this.searchWeiboListByAction(result)
            } else {
              const {discussList = []} = weiboList,
                date = new Date(discussList[discussList.length - 1].workdate)
              this.getWeiboListByAction({type: blogType}, {endDate: DateFormat(DateAddition(date, -1, "day"), "yyyy-MM-dd")})
            }
          } else {
            others = {type: blogType},
              result = {
                currentPage: currentPage + 1
              }
            this.getWeiboListByAction(others, result)
          }
        } else {
          const {startDate, endDate, content} = params
          result = {
            startDate: DateFormat(startDate, "yyyy-MM-dd"),
            endDate: DateFormat(endDate, "yyyy-MM-dd"),
            content: content,
            currentPage: 1,
          }
          this.searchWeiboListByAction(result)
          this.props.changeReset(true)
          this.setState({searching: true, searchForm: result, startSearch: true, weiboType: weiboType})
        }
        break;
      default:
        break;
    }

    this.setState({startSearch: false})
    this.props.changeReset(false)
  }

  getWeiboListByAction(others, params) {
    if(params.groupId=='1'){
      if(!params.startDate){
        params.startDate = this.state.startDate;
      }
      if(!params.endDate){
        params.endDate = this.state.endDate;
      }
    }
    let {getWeiboList,getSearchConditionByGroupIdInit} = this.props.blogMyBlog;
    
    // if(params.isGroup=="1"){
    //   params.groupId = params.weiboType;;
    // }
    getWeiboList(others, params)
    if(this.props.cardType!=2){
        getSearchConditionByGroupIdInit(params)
    }
  }

  searchWeiboListByAction(params) {
    let {searchWeiboList} = this.props.blogMyBlog;
    searchWeiboList(params);
  }

  searchWeiboMainPageListByAction(params) {
    let {searchWeiboMainPageList} = this.props.blogMyBlog;
    searchWeiboMainPageList(params);
  }

  searchUnreadWeiboMainPageListByAction(params) {
    let {searchUnreadWeiboMainPageList} = this.props.blogMyBlog;
    searchUnreadWeiboMainPageList(params);
  }

  searchWeiboMainPageShareToMeListByAction(params) {
    let {searchWeiboMainPageShareToMeList} = this.props.blogMyBlog;
    searchWeiboMainPageShareToMeList(params);
  }

  searchWeiboMainPageAllListByAction(params) {
    let {searchWeiboMainPageAllList} = this.props.blogMyBlog;
    searchWeiboMainPageAllList(params);
  }

  changeWeiboType = (data, weiboType,isDef) => {
    let {cardType} = this.props,params={} 
    cardType==1?params = this.getFormParams():params;
    switch (cardType * 1) {
      case 1 :
        // switch (Math.abs(weiboType) * 1) {
        //   case 0 :
        //       params.groupId = "0";
        //       break;
        //   case 1 :
        //     params.groupId = "-1";
        //     break;
        //   case 2 :
        //     params.groupId = "-2";
        //     break;
        //   case 3 :
        //     params.groupId = "-3";
        //     break;
        //   default:
        //     console.log(weiboType,111);
        //     weiboType = isDef == "1"? weiboType-3:weiboType;
        //     console.log(weiboType,222);
           
        //     break;
        // }
        params.groupId =  weiboType;
        params.currentPage = 1;

        if(weiboType=='-5'){
            this.getWeiboListByAction({type: 11, status: true}, params)
        }else{
            this.getWeiboListByAction({type: cardType * 10 + (weiboType > 0 ? 1 : Math.abs(weiboType) * 1), status: true}, params)
        }


        this.setParams(cardType,weiboType,params)
        break;
      case 2 :
        switch (weiboType * 1) {
          case 1 :
            params = {endDate: DateFormat(new Date(), "yyyy-MM-dd")};
            break;
          case 2 :
            params = {currentPage: 1, type: "reply"};
            break;
          case 3 :
            params = {currentPage: 1, type: "zan"};
            break;
          case 4 :
            params = {currentPage: 1, type: 'at'};
            break;
          default:
            break;
        }
        this.getWeiboListByAction({type: cardType * 10 + weiboType * 1, status: true}, params)
        this.setParams(cardType,weiboType,params)
        break;
      default:
        break;
    }
   
   
  }
  fetchData = () => {
    const weiboList = this.props.weiboList;
    if (weiboList.__hasData){
      if(this.state.cardType==1){
        this.getWeiboList(this.selectedType, this.getFormParams())
      }else{
        this.getWeiboList(this.currentType, this.currentGroup)
      }
    }
  }

  setParams(cardType,weiboType,params){
    if(cardType==1){
      this.setState({
        searching: false,
        searchForm: {},
        startSearch: false,
        selectedKey: weiboType=="0"?null:weiboType,
        weiboGroup: params.groupId
      })
    }else{
      this.setState({
        searching: false,
        searchForm: {},
        startSearch: false,
        weiboType: weiboType=="0"?null:weiboType,
        weiboGroup: params.groupId
      })
    }
  }
}

export default RightContainer